<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="utf-8">
		<title>Hello world</title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}

			.box {
				position: fixed;
				top: 50%;
				left: 50%;
				margin-top: -40vh;
				margin-left: -40vw;
				width: 80vw;
				height: 80vh;
			}

			.edit-wrapper {
				position: absolute;
				top: 0;
				left: 0;
				z-index: -10;
				opacity: 0;
				/*z-index: 10;
    opacity: 1;*/
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				overflow: hidden;
			}

			.edit-wrapper.is-show {
				z-index: 10;
				opacity: 1;
			}

			.edit-content {
				position: absolute;
				z-index: 10;
				opacity: 1;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				transform-origin: center;
			}

			.edit-content .close-btn {
				position: absolute;
				z-index: 50;
				top: 40px;
				right: 40px;
				text-align: center;
				width: 32px;
				height: 32px;
				line-height: 30px;
				border: 1px solid #fff;
				border-radius: 50%;
				font-size: 24px;
				cursor: pointer;
				color: #fff;
				box-sizing: content-box;
			}

			.edit-content .xxb {
				position: absolute;
				z-index: 1;
				bottom: 10px;
				left: 0;
				right: 0;
				text-align: center;
				font-size: 30px;
				color: #409EFF;
			}

			.aa {
				width: 100%;
				height: 100%;
				opacity: 1;
			}

			.btn-box {
				position: fixed;
				top: 40px;
				left: 40px;
				z-index: 10;
			}
		</style>
	</head>

	<body>
		<div class="btn-box">
			<button onclick="showEditLineClick()">显示线</button>
			<button onclick="hideEdit()">隐藏</button>
      <button onclick="showAdd()">添加</button>
		</div>
		<div class="box">
			<div class="aa"></div>
			<div class="edit-wrapper">
				<div class="edit-content">
					<div class="close-btn" onclick="oEdit.close()">×</div>
					<div style="width:100%; height:100%;" class="imageContainer"></div>
					<div class="xxb"></div>
				</div>
			</div>
		</div>
		<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
		<script src="./static/hammer.js"></script>
		<script src="./static/cornerstone.min.js"></script>
		<script src="./static/cornerstoneMath.min.js"></script>
		<script src="./static/cornerstoneWADOImageLoader.min.js"></script>
		<script src="./static/cornerstoneWebImageLoader.min.js"></script>
		<script src="./static/cornerstoneTools.min.js"></script>
		<script src="./static/dicomParser.min.js"></script>
		<script>
			const baseUrl = "http://127.0.0.1:8000/static/js/";
			const image_uir = '111'

			var config = {
				"胸膜增厚": "rgb(255, 0, 255)",
				"纤维灶": "rgb(220, 20, 60)",
				"钙化": "rgb(148, 0, 211)",
				"骨折": "rgb(123, 104, 238)",
				"肺不张": "rgb(0, 0, 205)",
				"肿块": "rgb(30, 144, 255)",
				"结节": "rgb(184, 134, 11)",
				"肺气肿": "rgb(0, 139, 0)",
				"气胸": "rgb(139, 35, 35)",
				"PICC": "rgb(218, 165, 32)",
				"积液": "rgb(255, 140, 0)",
				"积气": "rgb(0, 0, 0)",
				"实变": "rgb(85, 107, 47)",
				"术后金属": "rgb(95, 158, 160)",
				"膈下游离气体": "rgb(9,113,175)",
				"肠道积气扩张": "rgb(4,248,194)",
				"肠道积液液平": "rgb(148, 0, 211)",
				"泌尿系统结石": "rgb(108,227,33)"
			}



			var infos = {
				'111_ctr': {
					center_x: 1277,
					heart_x_begin_left: 936,
					heart_x_end_right: 2100,
					heart_y_begin_left: 1531,
					heart_y_end_right: 1621,
					lung_x_begin: 170,
					lung_x_end: 2348,
					lung_y: 1565,
					ratio: 0.5344,
				},
				'111_current': [{
          "name": "纤维灶",
          mark: true,
          "confidence": 1.0,
          "xmin": 1791.5301292590002,
          "ymin": 1144.1843983500526,
          "xmax": 2205.530129259,
          "ymax": 1429.1843983500526
        }, {
          "name": "结节",
          mark: true,
          "confidence": 1.0,
          "xmin": 1685.046367851623,
          "ymin": 668.259659969088,
          "xmax": 1751.046367851623,
          "ymax": 733.259659969088
        }, {
          "name": "实变",
          mark: true,
          "confidence": 1.0,
          "xmin": 1211.2967542503864,
          "ymin": 895.5332302936631,
          "xmax": 1613.2967542503864,
          "ymax": 1159.533230293663
        }, {
          "name": "结节",
          mark: true,
          "confidence": 1.0,
          "xmin": 902.8114374034003,
          "ymin": 814.0710973724885,
          "xmax": 1049.8114374034003,
          "ymax": 964.0710973724885
        }]
			}

			window.onload = function() {
				_initCornerstone();

				aaInitCornerstone();
			}

			function _initCornerstone() {
				cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
				cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
				cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
				cornerstoneTools.external.cornerstone = cornerstone;
				cornerstoneTools.external.Hammer = Hammer;

				// Image Loader
				const config = {
					webWorkerPath: `${baseUrl}assets/image-loader/cornerstoneWADOImageLoaderWebWorker.js`,
					taskConfiguration: {
						decodeTask: {
							codecsPath: `${baseUrl}assets/image-loader/cornerstoneWADOImageLoaderCodecs.js`,
						},
					},
				};
				cornerstoneWADOImageLoader.webWorkerManager.initialize(config);
			}

			// 初始化影像
			function aaInitCornerstone() {
				let element = document.querySelector('.aa');
				cornerstone.enable(element);
				cornerstone.loadAndCacheImage(
					'wadouri:http://localhost:8088/static/data/1.2.840.1.19439.0.1000.20220101101114.1153.10000.3383340/1.2.840.113564.12312312360.2022010110184045329.1003000225002'
					).then(function(image) {
					var viewport = cornerstone.getDefaultViewportForImage(element, image);
					cornerstone.displayImage(element, image, viewport);
				});
				element.addEventListener('cornerstoneimagerendered', onImageRendered);
			}

			function onImageRendered(e) {
				oEdit.init(e);

        drawBoundingBox(infos[image_uir + '_current'], e.detail.canvasContext);
        drawCTR(infos[image_uir + '_ctr'], e.detail.canvasContext);
			}

      function drawBoundingBox(objects, context) {
            for (i = 0; i < objects.length; i++) {
                let confidence = objects[i]["confidence"]
                let name1 = objects[i]["name"]
                let color = config[name1]
                if (color == undefined) {
                    color = "rgb(0, 0, 0)"
                }
                if (confidence === 1) {
                    label = objects[i]["name"]
                } else {
                    label = objects[i]["name"] + " " + confidence.toString()
                }

                xmin = objects[i]["xmin"]
                ymin = objects[i]["ymin"]
                xmax = objects[i]["xmax"]
                ymax = objects[i]["ymax"]

                context.fillStyle = color;
                context.strokeStyle = color;
                context.lineWidth = 8;
                context.font = "60px 微软雅黑"
                context.beginPath();
                context.moveTo(xmin, ymin);
                context.lineTo(xmin, ymax);
                context.lineTo(xmax, ymax);
                context.lineTo(xmax, ymin);
                context.lineTo(xmin, ymin);
                context.fillText(label, xmin, ymin - 1)
                context.fillRect(xmin, ymin - 60, context.measureText(label).width, 60);
                context.closePath();
                context.stroke();
                context.fillStyle = "white"
                context.fillText(label, xmin, ymin - 1)
            }
        }
      function drawCTR(ctr, context) {
            context.beginPath();
            context.lineWidth = 16;
            context.strokeStyle = "green"
            context.moveTo(ctr["lung_x_begin"], ctr["lung_y"]);
            context.lineTo(ctr["lung_x_end"], ctr["lung_y"]);
            context.closePath();
            context.stroke();
            let centerX = (ctr["lung_x_begin"] + ctr["lung_x_end"]) / 2
            let Y = [ctr["lung_y"], ctr["heart_y_begin_left"], ctr["heart_y_end_right"]]
            let minY = Math.min(...Y)
            let maxY = Math.max(...Y)
            context.strokeStyle = "black"
            context.beginPath();
            context.moveTo(centerX, minY - 50);
            context.lineTo(centerX, maxY + 50);
            context.closePath();
            context.stroke();
            context.strokeStyle = "red"
            context.beginPath();
            context.moveTo(ctr["heart_x_begin_left"], ctr["heart_y_begin_left"]);
            context.lineTo(centerX, ctr["heart_y_begin_left"]);
            context.closePath();
            context.stroke();
            context.beginPath();
            context.moveTo(centerX, ctr["heart_y_end_right"]);
            context.lineTo(ctr["heart_x_end_right"], ctr["heart_y_end_right"]);
            context.closePath();
            context.stroke();
        }


			// 显示编辑线
			function showEditLineClick() {
				oEdit.show({
          data: {
            line: infos[image_uir + '_ctr'],
            rect: infos[image_uir + '_current']
          },
          showLine: true
        });
			}

			// 隐藏
			function hideEdit() {
				oEdit.close();
			}

      // 添加
      function showAdd() {
        oEdit.addRect('胸膜增厚');
      }


			const oEdit = {
            visible: false,
            isInit: false,

            // 是否添加矩形
            isAddRect: false,
            add: {
                name: '',
                top: 0,
                left: 0,
                downx: 0,
                downy: 0,
                xmin: 0,
                ymin: 0,
                xmax: 0,
                ymax: 0,
            },

            oCanvas: null,
            context: null,
            // 图片数据
            image: {
              ratio: 0,
              leftDis: 0,
              topDis: 0,
              width: 0,
              height: 0,
              file: null
            },
            // 是否显示线
            showLine: false,
            // 数据
            oldData: null,
            newData: null,
            startData: null,
            // 路径
            paths: [],
            oPath: null,
            // 显示
            show(options) {
                this.showLine = options.showLine; // 是否显示线
                this.oldData = JSON.parse(JSON.stringify(options.data));
                this.newData = JSON.parse(JSON.stringify(options.data));

                this.drawData();

                this.visible = true;

                // $('#submitBtn').hide();
                // $('#myNavbar > .nav').hide();
                // $('#aiZdJg input[type="checkbox"]').attr('disabled', true);
                // $('#cancelBtn').show();
                // $('#editRectBtn').text('保存');
            },
            // 画
            addRect(name) {
                this.isAddRect = true;
                this.add.name = name;
                // 清空画布
                this.oCanvas.width = this.oCanvas.width;
                // 绘制底图
                this.drawImage();
                this.visible = true;

                // $('#submitBtn').hide();
                // $('#myNavbar > .nav').hide();
                // $('#aiZdJg input[type="checkbox"]').attr('disabled', true);
                // $('#cancelBtn').show();
                // $('#editRectBtn').text('保存');
            },
            // 关闭
            close() {
                // $('#submitBtn').show();
                // $('#myNavbar > .nav').show();
                // $('#aiZdJg input[type="checkbox"]').attr('disabled', false);
                // $('#cancelBtn').hide();
                // $('#editRectBtn').text('编辑');
                this.visible = false;
            },
            // 保存
            save() {
                infos[image_uir + "ctr"] = this.newData.line;
                infos[image_uir + "_current"] = this.newData.rect;
                drawReload($('#ctr_select').is(':checked'));
                setXxb(infos[image_uir + "ctr"].ratio);
                this.close();
            },
            // 初始化
            async init(e) {
                if(this.isInit) {
                    return;
                }
                this.isInit = true;
                this.initImageData(e);
                await waitTimeout(50);

                this.initEvent();
            },
            initEvent() {
              var context = this.context;
              var isDown = false;
              var downx = 0, downy = 0;

              $(this.oCanvas).on('mousedown', (e) => {
                if(!this.visible) {
                    return;
                }
                var canvas = this.oCanvas;
                var rect = canvas.getBoundingClientRect();
                var x = e.clientX - rect.left;
                var y = e.clientY - rect.top;
                if(this.isAddRect) {
                    isDown = true;
                    this.add.left = rect.left;
                    this.add.top = rect.top;
                    this.add.downx = e.pageX;
                    this.add.downy = e.pageY;
                } else {
                  this.paths.forEach((item) => {
                    if(context.isPointInPath(item.path, x, y)) {
                      this.oPath = item;
                      isDown = true;
                      this.startData = JSON.parse(JSON.stringify(this.newData));
                      downx = e.pageX;
                      downy = e.pageY;
                    }
                  })
                }
              })

              $(this.oCanvas).on('mousemove', (e) => {
                if(!this.visible) {
                    return;
                }
                if(this.isAddRect && isDown) {
                    let movex = e.pageX - this.add.downx;
                    let movey = e.pageY - this.add.downy;
                    this.add.xmin = this.add.downx - this.add.left;
                    this.add.ymin = this.add.downy - this.add.top;
                    this.add.xmax = this.add.downx + movex - this.add.left;
                    this.add.ymax = this.add.downy + movey - this.add.top;
                    this.drawAddRect();
                } else {
                  // 如果当前是按下
                  if(isDown) {
                    var movex = e.pageX - downx;
                    var movey = e.pageY - downy;
                    if(this.oPath.type == 'line') {
                      this.saveLineData(this.oPath.key, this.oPath.dir, movex/this.image.ratio, movey/this.image.ratio);
                    } else if (this.oPath.type == 'rect') {
                      this.saveRectData(this.oPath, movex/this.image.ratio, movey/this.image.ratio);
                    }
                  } else { // 非按下，移动改变canvas鼠标形状
                    var canvas = this.oCanvas;
                    var rect = canvas.getBoundingClientRect();
                    var x = e.clientX - rect.left;
                    var y = e.clientY - rect.top;
                    for(var i = 0; i < this.paths.length; i++) {
                      var item = this.paths[i];
                      if(context.isPointInPath(item.path, x, y)) {
                        canvas.style.cursor = item.cursor;
                        break;
                      } else {
                        canvas.style.cursor = '';
                      }
                    }
                  }
                }
              })

              window.addEventListener('mouseup', () => {
                if(!this.visible) {
                    return;
                }
                isDown = false;
                // 如果是添加矩形，鼠标抬起后，绘制可拖拽数据
                if(this.isAddRect) {
                  let rectData = JSON.parse(JSON.stringify(infos[image_uir + '_current']));
                  rectData.push({
                    name: this.add.name,
                    mark: true,
                    confidence: 1.0,
                    xmin: (this.add.xmin-this.image.leftDis)/this.image.ratio,
                    ymin: (this.add.ymin-this.image.topDis)/this.image.ratio,
                    xmax: (this.add.xmax-this.image.leftDis)/this.image.ratio,
                    ymax: (this.add.ymax-this.image.topDis)/this.image.ratio,
                  })
                  this.isAddRect = false;
                  oEdit.show({
                    data: {
                      line: infos[image_uir + '_ctr'],
                      rect: rectData
                    },
                    showLine: true
                  });
                }
              })
            },

            // 初始化图片宽高
            initImageData(e) {
              // 保存图片宽高
              this.image.width = e.detail.image.width;
              this.image.height = e.detail.image.height;              
              // 保存比例
              this.image.ratio = e.detail.viewport.scale;
              // 保存cavnas节点
              this.oCanvas = e.target.querySelector('canvas');
              // 保存canvas绘画对象
              this.context = e.detail.canvasContext;
              // 保存图片
              var base64 = this.oCanvas.toDataURL('image/png');
              var img = new Image();
              img.src = base64;
              img.onload = () => {
                this.image.file = img;
                this.image.leftDis = (img.width-this.image.width*this.image.ratio)/2;
                this.image.topDis = (img.height-this.image.height*this.image.ratio)/2;
              }
            },

            // 保存线数据
            saveLineData(key, dir, movex, movey) {
                let oLine = this.newData.line;
                let startLine = this.startData.line;
                // 保存线位置数据
                oLine[key] = (dir == 'x' ? movex : movey) + startLine[key];
                // 计算心胸比
                oLine.ratio = (oLine.heart_x_end_right - oLine.heart_x_begin_left) / (oLine.lung_x_end - oLine.lung_x_begin);

                // 画数据
                this.drawData();
            },

            // 保存矩形数据
            saveRectData(path, movex, movey) {
                let oRect = this.newData.rect;
                let startRect = this.startData.rect;
                var index = path.index;
                if(path.dir == 'xy') {
                    oRect[index].xmin = movex+startRect[index].xmin;
                    oRect[index].xmax = movex+startRect[index].xmax;
                    oRect[index].ymin = movey+startRect[index].ymin;
                    oRect[index].ymax = movey+startRect[index].ymax;
                } else {
                    oRect[index][path.key] = (path.dir == 'x' ? movex : movey)+startRect[index][path.key];
                }

                // 画数据
                this.drawData();
            },

            // 画数据
            drawData() {
                this.paths = [];
                // 清空画布
                this.oCanvas.width = this.oCanvas.width;
                // 绘制底图
                this.drawImage();
                // 画线，画框
                this.drawRect(this.newData.rect);
                if(this.showLine) {
                    this.drawLine(this.newData.line);
                }
            },

            // 绘制底图
            drawImage() {
              this.context.drawImage(this.image.file,0,0);
            },

            // 画线
            drawLine(data) {
              var ctr = {
                lung_x_begin: data.lung_x_begin*this.image.ratio+this.image.leftDis,
                lung_x_end: data.lung_x_end*this.image.ratio+this.image.leftDis,
                lung_y: data.lung_y*this.image.ratio+this.image.topDis,
                heart_x_begin_left: data.heart_x_begin_left*this.image.ratio+this.image.leftDis,
                heart_x_end_right: data.heart_x_end_right*this.image.ratio+this.image.leftDis,
                heart_y_begin_left: data.heart_y_begin_left*this.image.ratio+this.image.topDis,
                heart_y_end_right: data.heart_y_end_right*this.image.ratio+this.image.topDis,
              };
              var context = this.context;
              var paths = [];

              var path = null;

              let size1 = 15*this.image.ratio;
              let size2 = 20*this.image.ratio;
              let size3 = 8*this.image.ratio;
              let size4 = 50*this.image.ratio;

              context.beginPath();
              context.lineWidth = size1;
              context.strokeStyle = "green"
              context.moveTo(ctr.lung_x_begin, ctr.lung_y);
              context.lineTo(ctr.lung_x_end, ctr.lung_y);
              context.closePath();
              context.stroke();

              // 绿色中线
              path = new Path2D();
              path.moveTo(ctr.lung_x_begin+size2, ctr.lung_y-size3);
              path.lineTo(ctr.lung_x_end-size2, ctr.lung_y-size3);
              path.lineTo(ctr.lung_x_end-size2, ctr.lung_y+size3);
              path.lineTo(ctr.lung_x_begin+size2, ctr.lung_y+size3);
              paths.push({
                type: 'line',
                cursor: 'n-resize',
                dir: 'y',
                path: path,
                key: 'lung_y'
              });
              // 绿色左
              path = new Path2D();
              path.moveTo(ctr.lung_x_begin, ctr.lung_y-size3);
              path.lineTo(ctr.lung_x_begin+size2, ctr.lung_y-size3);
              path.lineTo(ctr.lung_x_begin+size2, ctr.lung_y+size3);
              path.lineTo(ctr.lung_x_begin, ctr.lung_y+size3);
              console.log(ctr.lung_x_begin, ctr.lung_y-size3)
              console.log(ctr.lung_x_begin+size2, ctr.lung_y-size3)
              console.log(ctr.lung_x_begin+size2, ctr.lung_y+size3)
              console.log(ctr.lung_x_begin, ctr.lung_y+size3)
              paths.push({
                type: 'line',
                cursor: 'e-resize',
                dir: 'x',
                path: path,
                key: 'lung_x_begin'
              });
              // 绿色右
              path = new Path2D();
              path.moveTo(ctr.lung_x_end-size2, ctr.lung_y-size3);
              path.lineTo(ctr.lung_x_end, ctr.lung_y-size3);
              path.lineTo(ctr.lung_x_end, ctr.lung_y+size3);
              path.lineTo(ctr.lung_x_end-size2, ctr.lung_y+size3);
              paths.push({
                type: 'line',
                cursor: 'e-resize',
                dir: 'x',
                path: path,
                key: 'lung_x_end'
              });


              centerX = (ctr.lung_x_begin + ctr.lung_x_end) / 2
              Y = [ctr.lung_y, ctr.heart_y_begin_left, ctr.heart_y_end_right]
              minY = Math.min(...Y)
              maxY = Math.max(...Y)
              context.strokeStyle = "black"
              context.beginPath();
              context.moveTo(centerX, minY - size4);
              context.lineTo(centerX, maxY + size4);
              context.closePath();
              context.stroke();


              context.strokeStyle = "red"
              context.beginPath();
              context.moveTo(ctr.heart_x_begin_left, ctr.heart_y_begin_left);
              context.lineTo(centerX, ctr.heart_y_begin_left);
              context.closePath();
              context.stroke();

              // 红色线
              path = new Path2D();
              path.moveTo(ctr.heart_x_begin_left+size2, ctr.heart_y_begin_left-size3);
              path.lineTo(centerX, ctr.heart_y_begin_left-size3);
              path.lineTo(centerX, ctr.heart_y_begin_left+size3);
              path.lineTo(ctr.heart_x_begin_left+size2, ctr.heart_y_begin_left+size3);
              paths.push({
                type: 'line',
                cursor: 'n-resize',
                dir: 'y',
                path: path,
                key: 'heart_y_begin_left'
              });
              // 红色左
              path = new Path2D();
              path.moveTo(ctr.heart_x_begin_left, ctr.heart_y_begin_left-size3);
              path.lineTo(ctr.heart_x_begin_left+size2, ctr.heart_y_begin_left-size3);
              path.lineTo(ctr.heart_x_begin_left+size2, ctr.heart_y_begin_left+size3);
              path.lineTo(ctr.heart_x_begin_left, ctr.heart_y_begin_left+size3);
              paths.push({
                type: 'line',
                cursor: 'e-resize',
                dir: 'x',
                path: path,
                key: 'heart_x_begin_left'
              });

              context.beginPath();
              context.moveTo(centerX, ctr.heart_y_end_right);
              context.lineTo(ctr.heart_x_end_right, ctr.heart_y_end_right);
              context.closePath();
              context.stroke();
          
              // 红色线
              path = new Path2D();
              path.moveTo(centerX, ctr.heart_y_end_right-size3);
              path.lineTo(ctr.heart_x_end_right-size2, ctr.heart_y_end_right-size3);
              path.lineTo(ctr.heart_x_end_right-size2, ctr.heart_y_end_right+size3);
              path.lineTo(centerX, ctr.heart_y_end_right+size3);
              paths.push({
                type: 'line',
                cursor: 'n-resize',
                dir: 'y',
                path: path,
                key: 'heart_y_end_right'
              });
              // 红色右
              path = new Path2D();
              path.moveTo(ctr.heart_x_end_right-size2, ctr.heart_y_end_right-size3);
              path.lineTo(ctr.heart_x_end_right, ctr.heart_y_end_right-size3);
              path.lineTo(ctr.heart_x_end_right, ctr.heart_y_end_right+size3);
              path.lineTo(ctr.heart_x_end_right-size2, ctr.heart_y_end_right+size3);
              paths.push({
                type: 'line',
                cursor: 'e-resize',
                dir: 'x',
                path: path,
                key: 'heart_x_end_right'
              });

              this.paths.push(...paths.reverse());
            },

            // 画矩形
            drawRect(data) {
                var list = data;
                var context = this.context;
                var paths = [];

                var path = null;

                for(var i = 0; i < list.length; i++) {
                    var item = list[i];
                    if(!item.mark) {
                        continue;
                    }
                    var confidence = item.confidence;
                    var label = item.name;
                    var color = config[label];

                    if (confidence !== 1) {
                        label = label + " " + confidence;
                    }
                    var xmin = item.xmin*this.image.ratio+this.image.leftDis;
                    var ymin = item.ymin*this.image.ratio+this.image.topDis;
                    var xmax = item.xmax*this.image.ratio+this.image.leftDis;
                    var ymax = item.ymax*this.image.ratio+this.image.topDis;

                    var size1 = 60*this.image.ratio;
                    var size2 = 8*this.image.ratio;
                    var size3 = 4*this.image.ratio;

                    context.fillStyle = color;
                    context.strokeStyle = color;
                    context.lineWidth = size2;
                    context.font = size1+"px 微软雅黑"
                    context.beginPath();
                    context.moveTo(xmin, ymin);
                    context.lineTo(xmin, ymax);
                    context.lineTo(xmax, ymax);
                    context.lineTo(xmax, ymin);
                    context.lineTo(xmin, ymin);
                    context.fillText(label, xmin, ymin - 1)
                    context.fillRect(xmin, ymin - size1, context.measureText(label).width, size1);
                    context.closePath();
                    context.stroke();
                    context.fillStyle = "white"
                    context.fillText(label, xmin, ymin - 1);

                    // 添加path
                    // 上
                    path = new Path2D();
                    path.moveTo(xmin+size3, ymin-size3);
                    path.lineTo(xmax-size3, ymin-size3);
                    path.lineTo(xmax-size3, ymin+size3);
                    path.lineTo(xmin+size3, ymin+size3);
                    paths.push({
                        type: 'rect',
                        cursor: 'n-resize',
                        dir: 'y',
                        path: path,
                        key: 'ymin',
                        index: i
                    });
                    // 右
                    path = new Path2D();
                    path.moveTo(xmax-size3, ymin+size3);
                    path.lineTo(xmax-size3, ymax-size3);
                    path.lineTo(xmax+size3, ymax+size3);
                    path.lineTo(xmax+size3, ymin-size3);
                    paths.push({
                        type: 'rect',
                        cursor: 'e-resize',
                        dir: 'x',
                        path: path,
                        key: 'xmax',
                        index: i
                    });
                    // 下
                    path = new Path2D();
                    path.moveTo(xmin+size3, ymax-size3);
                    path.lineTo(xmax-size3, ymax-size3);
                    path.lineTo(xmax-size3, ymax+size3);
                    path.lineTo(xmin+size3, ymax+size3);
                    paths.push({
                        type: 'rect',
                        cursor: 's-resize',
                        dir: 'y',
                        path: path,
                        key: 'ymax',
                        index: i
                    });
                    // 左
                    path = new Path2D();
                    path.moveTo(xmin-size3, ymin+size3);
                    path.lineTo(xmin-size3, ymax-size3);
                    path.lineTo(xmin+size3, ymax-size3);
                    path.lineTo(xmin+size3, ymin+size3);
                    paths.push({
                        type: 'rect',
                        cursor: 'w-resize',
                        dir: 'x',
                        path: path,
                        key: 'xmin',
                        index: i
                    });
                    // 中心
                    path = new Path2D();
                    path.moveTo(xmin+size3, ymin+size3);
                    path.lineTo(xmin+size3, ymax-size3);
                    path.lineTo(xmax-size3, ymax-size3);
                    path.lineTo(xmax-size3, ymin+size3);size3
                    path.lineTo(xmin+size3, ymin+size3);
                    paths.push({
                        type: 'rect',
                        cursor: 'move',
                        dir: 'xy',
                        path: path,
                        index: i
                    });
                }
                this.paths.push(...paths.reverse());
            },

            // 画添加矩形
            drawAddRect() {
                // 清空画布
                this.oCanvas.width = this.oCanvas.width;
                // 绘制底图
                this.drawImage();

                let xmin = this.add.xmin;
                let ymin = this.add.ymin;
                let xmax = this.add.xmax;
                let ymax = this.add.ymax;

                let label = this.add.name;
                let color = config[label];
                let context = this.context;

                var size1 = 60*this.image.ratio;
                var size2 = 8*this.image.ratio;
                var size3 = 4*this.image.ratio;

                context.fillStyle = color;
                context.strokeStyle = color;
                context.lineWidth = size2;
                context.font = size1+"px 微软雅黑"
                context.beginPath();
                context.moveTo(xmin, ymin);
                context.lineTo(xmin, ymax);
                context.lineTo(xmax, ymax);
                context.lineTo(xmax, ymin);
                context.lineTo(xmin, ymin);
                context.fillText(label, xmin, ymin - 1)
                context.fillRect(xmin, ymin - size1, context.measureText(label).width, size1);
                context.closePath();
                context.stroke();
                context.fillStyle = "white"
                context.fillText(label, xmin, ymin - 1);
            },

            // 获取图片
            getImageFile(data) {
                this.showLine = true; // 是否显示线
                this.oldData = JSON.parse(JSON.stringify(data));
                this.newData = JSON.parse(JSON.stringify(data));

                this.drawData();

                // 保存图片
                var base64 = this.oCanvas.toDataURL('image/png');
                return base64ToFile(base64, '数据.png');
            }
          }


          const waitTimeout = function (time) {
            return new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve();
              }, time);
            })
          }

          // base64转文件
          function base64ToFile(base64, fileName) {
            var arr = base64.split(','),
              mime = arr[0].match(/:(.*?);/)[1],
              bstr = atob(arr[1]),
              n = bstr.length,
              u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            var theBlob = new Blob([u8arr], { type: mime });
            theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
            theBlob.name = fileName;                // 文件名
            return new File([theBlob], fileName, {type: theBlob.type, lastModified: Date.now()});
          }
		</script>
	</body>

</html>
